import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as Resp;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ty_smart_watch/bean/login_bean.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/page/login/login_page.dart';
import 'package:ty_smart_watch/page/my_home_page.dart';
import 'package:ty_smart_watch/route/routes.dart';
import 'package:ty_smart_watch/utils/Log.dart';

import 'common/common.dart';
import 'utils/http_util.dart';

// void main() {
//   runApp(const MyApp());
// }
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(
    [
      DeviceOrientation.portraitUp, // 竖屏 Portrait 模式
      DeviceOrientation.portraitDown,
      // DeviceOrientation.landscapeLeft, // 横屏 Landscape 模式
      // DeviceOrientation.landscapeRight,
    ],
  );
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  late final AppLifecycleListener _listener;

  @override
  void initState() {
    super.initState();
// Initialize the AppLifecycleListener class and pass callbacks
    _listener = AppLifecycleListener(
      onStateChange: _onStateChanged,
    );
  }

  @override
  void dispose() {
    // Do not forget to dispose the listener
    _listener.dispose();
    super.dispose();
  }

// Listen to the app lifecycle state changes
  void _onStateChanged(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.detached:
        Log.d('App detached');
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          // 在下一帧中执行断开逻辑
          // 这将确保应用关闭之前有足够的时间来断开连接
          // 在此处执行断开逻辑的代码
          Log.d('App addPostFrameCallback');
          BleUtil.disconnectAllDevice();
        });
        break;
      case AppLifecycleState.resumed:
        Log.d('App resumed');
        break;
      case AppLifecycleState.inactive:
        Log.d('App inactive');
        break;
      case AppLifecycleState.hidden:
        Log.d('App hidden');
        break;
      case AppLifecycleState.paused:
        Log.d('App paused');
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      builder: FlutterSmartDialog.init(),
      // initialRoute: Routes.initial,
      getPages: AppPages.pages,
      title: 'Light Things',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      // home: MyHomePage(),
      home: FutureBuilder<bool>(
        future: _hasUser(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const SizedBox();
          }
          if (snapshot.hasError) {
            return const Text('Error');
          }
          if (snapshot.data!) {
            Log.d("snapshot.data! > ${snapshot.data!}");
            return const MyHomePage();
          } else {
            Log.d("snapshot.data! > ${snapshot.data!}");
            return const LoginPage();
          }
        },
      ),
    );
  }

  Future<bool> _hasUser() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String accessToken = prefs.getString(SP_ACCESS_TOKEN) ?? "";
    String refreshToken = prefs.getString(SP_REFRESH_TOKEN) ?? "";
    if (accessToken.isNotEmpty || refreshToken.isNotEmpty) {
      var dio = HttpUtil.instance?.serviceDio();
      dio.options.headers['tenant-id'] = "1";
      dio.options.headers['Authorization'] = accessToken;

      // 定义查询参数
      Map<String, dynamic> queryParameters = {'refreshToken': refreshToken};

      Resp.Response response =
          await dio.post("/member/auth/refresh-token", queryParameters: queryParameters);
      print("更新Token结果 ： $response");
      bool res = false;
      try {
        Map<String, dynamic> loginMap = jsonDecode(response.toString());
        LoginBean loginBean = LoginBean.fromJson(loginMap);
        if (loginBean.code == 0) {
          //刷新token成功
          prefs.setInt(SP_USER_ID, loginBean.data?.userId ?? -1);
          prefs.setString(SP_ACCESS_TOKEN, loginBean.data?.accessToken ?? "");
          prefs.setString(SP_REFRESH_TOKEN, loginBean.data?.refreshToken ?? "");
          res = true;
        } else {
          res = false;
        }
      } catch (e) {
        print("e: $e");
      }
      return res;
    } else {
      return false;
    }
    // bool hasUser = accessToken.isNotEmpty || refreshToken.isNotEmpty;
    // Log.d("has user : $hasUser");
    // return hasUser;
  }
}
